//
//  L_Phone_PwdVC.swift
//  letuofu
//
//  Created by dooland2 on 2020/7/23.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class L_Phone_PwdVC: BaseViewControllerWithHeader,NTESVerifyCodeManagerDelegate {
    var manager = NTESVerifyCodeManager.getInstance()
    var smsVerifyCredential = ""
    var phoneLab = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "修改密码"
        drawRightButton(imageName: "xiangqingkefu_82")
        .addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                              pointOffset: .init(x: -0.5, y: 1),  color: .xE0551B)
        

        
        let bgview = safeView.drawView({ (make) in
            make.top.equalTo(headView.snp_bottom).offset(26)
            make.left.right.equalToSuperview()
            make.height.equalTo(62)
        })
        bgview.backgroundColor = .white
        
        bgview.drawLabel(label: phoneLab, text: LocalStorage.getString(forKey: LOGIN_ID), fontSize: 15, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
        }
        
        let btn = safeView.drawButton(title: "下一步", titleColor: .white, fontSize: 15) { (make) in
            make.top.equalTo(bgview.snp.bottom).offset(23)
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(35)
        }
        btn.backgroundColor = .xFC4C02
        btn.layer.cornerRadius = 7
        btn.addTarget(self, action: #selector(_submiButtonClick(button:)), for: .touchUpInside)
    }
}


// MARK: event & action
extension L_Phone_PwdVC {
    //计算一次时间不用每次打开时间都获取
    func getTimeOutWithDate() -> Bool {
        let now = Date().timeIntervalSince1970
        if let lastTime = LocalStorage.getDouble(forKey: SEND_SMS),let timeNumber = anyToDouble(now-lastTime) {
            if timeNumber > 60.0 {
                return true
            }
            else {
                return false
            }
        }
        return true
    }
    
    @objc func _kefuButtonClick(button: Button) {
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")

        vc.headTitle.text = "联系客服"
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func _submiButtonClick(button: Button) {
        if !getTimeOutWithDate() {
            let popup = PopupBox(infoText: "同一手机号码限制1分钟内只能发送一次短信验证")
            popup.show(vc: UIViewController.topMostController() ?? self)
            return
        }

        let now = Date().timeIntervalSince1970
        LocalStorage.saveDouble(anyToDouble(now), forKey: SEND_SMS)
        codeAction()
    }
    
    
    func codeAction() {
                // 如果需要了解组件的执行情况,则实现回调
        manager?.delegate = self
                
                // captchaid的值是每个产品从后台生成的,比如 @"a05f036b70ab447b87cc788af9a60974"
                
                // 传统验证码
                let captchaid = CAPTCHA_ID
        manager?.mode = .normal
                
                // 无感知验证码
        //        NSString *captchaid = @"6a5cab86b0eb4c309ccb61073c4ab672";
        //        self.manager.mode = NTESVerifyCodeBind;
                
        manager?.configureVerifyCode(captchaid, timeout: 7.0)
                
                // 设置语言
        manager?.lang = .CN
                
                // 设置透明度
        manager?.alpha = 0.3
                
                // 设置颜色
        manager?.color = UIColor.black
                
                // 设置frame
        manager?.frame = CGRect.null
                
                // 是否开启降级方案
        manager?.openFallBack = true
        manager?.fallBackCount = 3
                
                // 显示验证码
        manager?.openVerifyCodeView()
    }

    /**
     * 验证码组件初始化完成
     */
    
    func verifyCodeInitFinish() {
        print("收到初始化完成的回调")
    }
    
    /**
    * 验证码组件初始化出错
    *
    * @param message 错误信息
    */
    func verifyCodeInitFailed(_ error: [Any]!) {
        print("收到错误信息的回调")
    }
    
    /**
    * 完成验证之后的回调
    *
    * @param result 验证结果 BOOL:YES/NO
    * @param validate 二次校验数据，如果验证结果为false，validate返回空
    * @param message 结果描述信息
    *
    */
    func verifyCodeValidateFinish(_ result: Bool, validate: String!, message: String!) {
        if result {
            print("完成验证之后的回调")
            print(validate ?? "validate失败")
            print(message ?? "message失败")
            if phoneLab.text?.validateMobile() ?? false {
                API.sendVerifyCode(pCode: "110002", callback: { (dic) in
                    let vc = L_ChangePwdVC(phoneNum: self.phoneLab.text ?? "", smsVerifyCredential: dic?.getString("smsVerifyCredential") ?? "", vaildeCode: "")
                    self.pushViewController(vc)
                })

            }
            else {
            }
        }
    }
    

    /**
     * 关闭验证码窗口后的回调
     */
    func verifyCodeCloseWindow() {
        print("关闭验证码窗口后的回调")
        
    }
    
    /**
    * 网络错误
    *
    * @param error 网络错误信息
    */
    func verifyCodeNetError(_ error: Error!) {
        print("网络错误")
        
    }
}
